package org.sxf.app.sign.biz;

import android.content.Context;
import android.os.AsyncTask;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.util.LogUtils;

import org.sxf.app.sign.constants.Constants;
import org.sxf.app.sign.data.DataCacheSingleton;
import org.sxf.app.sign.model.CorpInfoBean;
import org.sxf.app.sign.model.LoginRepBean;
import org.sxf.app.sign.model.LoginReqBean;
import org.sxf.app.sign.model.MsgRepBean;
import org.sxf.app.sign.model.QueryCorpListRepBean;
import org.sxf.app.sign.model.QueryCorpListReqBean;
import org.sxf.app.sign.provider.Client;
import org.sxf.app.sign.provider.MsgHandler;
import org.sxf.app.sign.utils.ConfigFileUtilsSingleton;
import org.sxf.app.sign.utils.SystemUtils;
import org.sxf.app.sign.utils.Utility;

import java.util.HashMap;
import java.util.List;

import Ice.ConnectionRefusedException;
import Ice.SocketException;
import Ice.TimeoutException;
import Ice.UnknownException;

/**
 * Created by zqc on 17/1/16.
 */
public class LoginBiz extends BaseBiz {


    public final static int BIZ_LOGIN_QUERY_CORP_SUCCESS = 0x10;
    public final static int BIZ_GOTO_LOGIN_VIEW = 0x11;
    public final static int BIZ_CHECK_LOGIN_INFO_PASS = 0x12;
    public final static int BIZ_GOTO_SELECT_CORP_VIEW = 0x13;

    public final static int BIZ_LOGIN_PW_WRONG = 0x110;
    public final static int BIZ_LOGIN_FAIL = 0x111;
    public final static int BIZ_LOGIN_SUCCESS = 0x112;

    public final static int ERROR_QUERY_CORP_FAIL = 0xE10;
    public final static int ERROR_LOGIN_NET_ERROR = 0xE11;

    public LoginBiz(Context context, OnBizCallBackListener listener){
        this.mContext = context;
        this.mBizCallBackListener = listener;
    }

    public void checkLoginInfo(){

        String corpID = ConfigFileUtilsSingleton.getInstance().readConfig(Constants.CONFIG_KEY_SCHOOL_CODE);
        String userID = ConfigFileUtilsSingleton.getInstance().readConfig(Constants.CONFIG_KEY_STUDENT_NO);
        String token = ConfigFileUtilsSingleton.getInstance().readConfig(Constants.CONFIG_KEY_TOKEN);

        if ("".equals(corpID)){
            safeOnBizResult(BIZ_GOTO_SELECT_CORP_VIEW, null);
            queryCorpList();
            return;
        }

        DataCacheSingleton.getInstance().setSchoolCode(corpID);
        if ("".equals(userID) || "".equals(token)){
            safeOnBizResult(BIZ_GOTO_LOGIN_VIEW, null);
            return;
        }


        DataCacheSingleton.getInstance().setStudentNo(userID);
        DataCacheSingleton.getInstance().setTk(token);

        safeOnBizResult(BIZ_CHECK_LOGIN_INFO_PASS, null);

    }

    private String createQueryCorpListReqJson(){

        QueryCorpListReqBean bean = new QueryCorpListReqBean();
        bean.platform = Constants.PLATFORM;
        String reqStr = JSON.toJSONString(bean);

        return reqStr;
    }

    public void queryCorpList(){

        new AsyncTask<Void, Integer, String>() {
            @Override
            protected String doInBackground(Void... voids) {

                String reqStr = MsgHandler.msgEncode("00", createQueryCorpListReqJson(), MsgHandler.NO_NEED_TOKEN);

                String result = "";
                try {
                    LogUtils.d("send:" + reqStr);
                    result = Client.getServicePrx().queryCorpList(reqStr);
                    LogUtils.d("result: " + result);
                }catch (ConnectionRefusedException e){
                    LogUtils.e(Utility.getStackTrace(e));
                }catch(TimeoutException e){
                    LogUtils.e(Utility.getStackTrace(e));
                }catch (SocketException e){
                    LogUtils.e(Utility.getStackTrace(e));
                }catch (UnknownException e){
                    LogUtils.e(Utility.getStackTrace(e));
                }catch (Exception e){
                    LogUtils.e(Utility.getStackTrace(e));
                }

                return result;
            }
            @Override
            protected void onPostExecute(String result){
                if (mIsQuit){
                    return;
                }
                try {

                    if (result == null || "".equals(result)){
                        safeOnBizError(ERROR_QUERY_CORP_FAIL, null);
                        return;
                    }

                    MsgRepBean bean = checkMsg(result, false);
                    if (bean == null){
                        safeOnBizError(ERROR_QUERY_CORP_FAIL, null);
                        return;
                    }

                    QueryCorpListRepBean dataBean = JSON.parseObject(bean.rd, QueryCorpListRepBean.class);
                    if (dataBean == null || dataBean.corp_list == null){
                        safeOnBizError(ERROR_QUERY_CORP_FAIL, null);
                        return;
                    }
                    List<CorpInfoBean> corpList = JSON.parseArray(dataBean.corp_list, CorpInfoBean.class);

                    DataCacheSingleton.getInstance().setSchoolBeanList(corpList);

                    safeOnBizResult(BIZ_LOGIN_QUERY_CORP_SUCCESS, null);

                }catch (Exception e){
                    LogUtils.e(Utility.getStackTrace(e));
                    safeOnBizError(ERROR_QUERY_CORP_FAIL, null);
                    return;
                }

                return;
            }
        }.execute();
    }


    private String createLoginReqJson(){

        LoginReqBean bean = new LoginReqBean();
        bean.platform = Constants.PLATFORM;
        bean.dev_info = SystemUtils.getPhoneModel();
        bean.corp_id = DataCacheSingleton.getInstance().getSchoolCode();
        bean.usr_id = DataCacheSingleton.getInstance().getStudentNo();
        bean.pwd = DataCacheSingleton.getInstance().getPwMd5();
        String reqStr = JSON.toJSONString(bean);
        LogUtils.d("msg:" + reqStr);
        return reqStr;
    }

    public void login(){

        new AsyncTask<Void, Integer, String>() {
            @Override
            protected String doInBackground(Void... voids) {

                String reqStr = MsgHandler.msgEncode("00", createLoginReqJson(), MsgHandler.NO_NEED_TOKEN);

                String result = "";
                try {
                    LogUtils.d("send:" + reqStr);
                    result = Client.getServicePrx().login(reqStr);
                    LogUtils.d("result: " + result);
                }catch (ConnectionRefusedException e){
                    LogUtils.e(Utility.getStackTrace(e));
                }catch(TimeoutException e){
                    LogUtils.e(Utility.getStackTrace(e));
                }catch (SocketException e){
                    LogUtils.e(Utility.getStackTrace(e));
                }catch (UnknownException e){
                    LogUtils.e(Utility.getStackTrace(e));
                }catch (Exception e){
                    LogUtils.e(Utility.getStackTrace(e));
                }

                return result;
            }
            @Override
            protected void onPostExecute(String result){
                if (mIsQuit){
                    return;
                }
                try {

                    if (result == null || "".equals(result)){
                        safeOnBizError(ERROR_LOGIN_NET_ERROR, null);
                        return;
                    }

                    MsgRepBean bean = checkMsg(result, false);
                    if (bean == null){
                        safeOnBizError(ERROR_LOGIN_NET_ERROR, null);
                        return;
                    }

                    LoginRepBean dataBean = JSON.parseObject(bean.rd, LoginRepBean.class);
                    if (dataBean == null){
                        safeOnBizError(ERROR_LOGIN_NET_ERROR, null);
                        return;
                    }

                    if (dataBean.result.equals("1")){
                        safeOnBizResult(BIZ_LOGIN_PW_WRONG, null);
                        return;
                    }else if (!dataBean.result.equals("0")){
                        safeOnBizResult(BIZ_LOGIN_FAIL, null);
                        return;
                    }

                    if (dataBean.token.equals("")){
                        safeOnBizError(ERROR_LOGIN_NET_ERROR, null);
                        return;
                    }

                    DataCacheSingleton.getInstance().setTk(dataBean.token);
                    DataCacheSingleton.getInstance().setPwMd5("");

                    ConfigFileUtilsSingleton.getInstance().writeConfig(Constants.CONFIG_KEY_STUDENT_NO, DataCacheSingleton.getInstance().getStudentNo());
                    ConfigFileUtilsSingleton.getInstance().writeConfig(Constants.CONFIG_KEY_TOKEN, dataBean.token);

                    safeOnBizResult(BIZ_LOGIN_SUCCESS, null);

                }catch (Exception e){
                    LogUtils.e(Utility.getStackTrace(e));
                    safeOnBizError(ERROR_LOGIN_NET_ERROR, null);
                    return;
                }

                return;
            }
        }.execute();
    }



}
